import { Input, View } from '@tarojs/components';
import './index.less';
import { useState } from '@tarojs/taro';

const XInput = ({
  label,
  value,
  type,
  focus,
  placeholder,
  disabled,
  style,
  inputStyle,
  onChange
}) => {
  const [vl, setVl] = useState('');
  const onChangeValue = (e) => {
    setVl(e.detail.value);
    typeof onChange === 'function' && !disabled && onChange(e);
  };
  const onBlur = (e) => {
    if (disabled) {
      return;
    }
    const v = e.detail.value;
    if (!vl || vl.length < v.length) {
      setVl(v);
      onChange(e);
    }
  };

  return (
    <View className="xinput-view" style={style}>
      {label ? <View className="xinput-view-label">{label}</View> : null}
      <Input
        className="xinput-view-value input"
        type={type}
        focus={focus}
        value={value}
        onInput={onChangeValue}
        onBlur={onBlur}
        placeholder={placeholder}
        style={inputStyle}
      ></Input>
    </View>
  );
};
XInput.defaultProps = {
  label: '',
  value: '',
  placeholder: '',
  type: 'text',
  focus: false,
  style: {},
  inputStyle: {},
  disabled: false,
  onChange: () => {}
};
export default XInput;
